<template>
    <view class="home-page">
        <PublicHead title="实名认证"></PublicHead>
        <view class="form-box">
            <u--form
                labelPosition="left"
                :model="formData"
                :rules="rules"
                ref="uForm"
            >
                <div class="title">实名认证</div>
                <!-- <u-form-item label="姓    名" prop="certName" borderBottom>
                    <u--input
                        v-model="formData.certName"
                        border="none"
                        placeholder="请输入姓名"
                        placeholderStyle="color: #ddd;"
                    ></u--input>
                </u-form-item>
                <u-form-item label="身份证号" prop="certNo" borderBottom>
                    <u--input
                        v-model="formData.certNo"
                        placeholder="请输入身份证号"
                        placeholderStyle="color: #ddd;"
                        border="none"
                    ></u--input>
                </u-form-item> -->
                <u-form-item
                    label="选择省份"
                    prop="province"
                    @click="openModal"
                    ref="item1"
                >
                    <u--input
                        v-model="provinceValue"
                        disabled
                        disabledColor="#ffffff"
                        placeholder="请选择"
                        placeholderStyle="color: #ddd;"
                        border="none"
                    ></u--input>
                    <u-icon
                        slot="right"
                        name="arrow-right"
                        color="#c8c9cc"
                    ></u-icon>
                </u-form-item>
                <!-- <div class="province-tips">
                    <div>请选择微信所在省</div>
                </div> -->
                <div class="btn">
                    <u-button
                        type="success"
                        color="rgb(37, 195, 115)"
                        shape="circle"
                        :loading="loading"
                        @click="handleNext"
                        >开始实名</u-button
                    >
                </div>
            </u--form>
        </view>

        <u-action-sheet
            :show="showCityPicker"
            :actions="provinceColumns"
            @close="showCityPicker = false"
            @select="onSelect"
        >
        </u-action-sheet>
        <u-modal :show="showModal" :showConfirmButton="false">
            <view class="modal-content">
                <view class="qr-code">
                    <u-loading-page :loading="loading"></u-loading-page>
                    <canvas
                        v-if="!loading && qrContent"
                        class="code"
                        canvas-id="myQrcode"
                        style="background: white; width: 250rpx; height: 250rpx"
                    />
                </view>
                <view class="des"> 请使用微信扫一扫，进行实名 </view>
                <view class="error-text time-text">
                    有效期倒计时 {{ formatDuration(timeText) }}
                </view>
                <u-button
                    type="success"
                    color="rgb(37, 195, 115)"
                    shape="circle"
                    :loading="loadingBtn"
                    :disabled="isSuccess"
                    @click="handleAuthWeChat(false)"
                >
                    {{ isSuccess ? '已经实名成功' : '实名认证' }}
                </u-button>

                <view class="error-text not-close">请勿关闭弹窗</view>
                <u-modal :show="showCheckModal" :showConfirmButton="false">
                    <view class="modal-content-check">
                        <view class="tips-icon">
                            <view v-if="isSuccess" class="success">
                                <u-icon
                                    name="checkmark-circle"
                                    :size="32"
                                    color="#4CD863"
                                ></u-icon>
                                <view style="margin-bottom: 30px"
                                    >实名成功</view
                                >
                            </view>
                            <view v-else class="fail">
                                <u-icon
                                    name="close-circle"
                                    :size="32"
                                    color="#FF3B2F"
                                ></u-icon>
                                <view>实名失败</view>
                            </view>
                        </view>
                        <!-- <view v-if="isSuccess" class="des-success">
                            恭喜你，实名认证成功
                        </view>
                        <template v-else>
                            <view>请确认微信扫码登录成功，</view>
                            <view class="fail-des"
                                >并且微信与实名信息是一致。</view
                            >
                        </template> -->
                        <view style="width: 100px">
                            <u-button
                                type="success"
                                shape="circle"
                                color="rgb(37, 195, 115)"
                                @click="onSave"
                            >
                                确认
                            </u-button>
                        </view>
                    </view>
                </u-modal>
            </view>
        </u-modal>
    </view>
</template>

<script>
import QRCode from './weapp.qrcode.esm';
import PublicHead from './public-head/index';
import { getProvinceList, getQrcode, confirmLogin } from './mock';
export default {
    components: { PublicHead },
    data() {
        const validateIdCard = (idCard) => {
            // 18位身份证号正则表达式
            const regExp =
                /^[1-9]\d{5}(19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[xX\d]$/;
            return regExp.test(idCard);
        };
        const validatorMessage = (val) => {
            if (!validateIdCard(val)) {
                return '请输入正确的身份证号码';
            }
        };
        return {
            qrCodeSrc: '', // 用于存储生成的二维码图片的base64字符串
            formData: {
                certName: '',
                certNo: '',
                province: '',
                uuid: '',
            },
            rules: {
                certNo: {
                    validator: validatorMessage,
                },
            },
            actions: [
                {
                    name: '男',
                },
                {
                    name: '女',
                },
                {
                    name: '保密',
                },
            ],
            qrContent: '',
            showCityPicker: false,
            showModal: false,
            showCheckModal: false,
            isSuccess: false,
            loading: false,
            loadingBtn: false,
            hasChecked: false,
            userId: '',
            timeText: 0,
            provinceColumns: [],
        };
    },
    computed: {
        provinceValue() {
            const target = this.provinceColumns.find(
                (item) => item.value === this.formData.province
            );
            return target?.name;
        },
    },
    onReady() {
        //如果需要兼容微信小程序，并且校验规则中含有方法等，只能通过setRules方法设置规则。
        this.$refs.uForm.setRules(this.rules);
    },
    onLoad(params) {
        this.userId = params.id;
        this.init();
    },
    methods: {
        //绘制二维码
        handleQrCode() {
            const options =
                ('canvas',
                {
                    width: 250,
                    height: 250,
                    canvasId: 'myQrcode',
                    text: this.qrContent, //这是绘制二维码的字符串
                });
            QRCode(options);
        },
        //该方法主要是将px单位转换为rpx
        createRpx2px(rpx) {
            return (wx.getSystemInfoSync().windowWidth / 750) * rpx;
        },
        // 倒计时
        setTimeLoop() {
            this.timeText--;
            // 检查成功就停止
            if (this.hasChecked) return;

            // 检测或者1分钟到了就停止
            if (this.timeText > 0) {
                setTimeout(() => {
                    this.setTimeLoop();
                }, 1000);
            } else {
                this.handleAuthWeChat(true);
            }
        },
        // 下一步
        handleNext() {
            const that = this;
            // this.$refs.uForm
            //     .validate()
            //     .then((res) => {
            const params = {
                certName: this.formData.certName,
                certNo: this.formData.certNo,
                province: this.formData.province,
                key: this.userId,
            };
            that.loading = true;
            that.hasChecked = false;
            that.qrContent = '';
            that.formData.uuid = '';
            that.timeText = 180; //倒计时3分钟

            // 获取二维码
            getQrcode(params)
                .then((res) => {
                    if (res?.data?.uuid) {
                        that.formData.uuid = res.data.uuid;
                        that.qrContent = res.data.qrContent;
                        that.showModal = true;
                        that.handleQrCode();
                        that.setTimeLoop();
                    } else {
                        uni.$u.toast(res.msg);
                    }
                })
                .catch((err) => {
                    console.error(err);
                })
                .finally(() => {
                    that.loading = false;
                });
            // })
            // .catch((errors) => {
            //     uni.$u.toast('校验失败');
            // });
        },
        // 格式化时间
        formatDuration(totalSeconds) {
            const days = Math.floor(totalSeconds / (24 * 60 * 60));
            totalSeconds %= 24 * 60 * 60;

            const hours = Math.floor(totalSeconds / (60 * 60));
            totalSeconds %= 60 * 60;

            const minutes = Math.floor(totalSeconds / 60);
            const seconds = totalSeconds % 60;
            let dateTime = '';
            if (days > 0) {
                dateTime += `${days}天 `;
            }
            if (hours > 0 || days > 0) {
                dateTime += `${hours}小时 `;
            }
            if (minutes > 0 || hours > 0 || days > 0) {
                dateTime += `${minutes}分钟 `;
            }
            dateTime += `${seconds}秒`;

            return dateTime;
        },
        handleAuthWeChat(isAutoSubmit = false) {
            this.loadingBtn = true;
            this.isSuccess = false;
            const params = {
                uuid: this.formData.uuid,
                certName: this.formData.certName,
                certNo: this.formData.certNo,
                province: this.formData.province,
                user_id: this.userId,
            };
            confirmLogin(params)
                .then((res) => {
                    this.isSuccess = res.code === 1;
                    // 成功则暂停倒计时
                    if (this.isSuccess) {
                        this.hasChecked = true;
                    }
                    // 手动成功、自动检测都要显示弹窗
                    if (this.isSuccess || isAutoSubmit) {
                        this.showCheckModal = true;
                    } else {
                        // 手动检测失败则提示失败信息
                        uni.$u.toast(res.msg);
                    }
                })
                .catch((err) => {
                    console.error(err);
                })
                .finally(() => {
                    this.loadingBtn = false;
                });
        },
        onSave() {
            this.showCheckModal = false;
            this.showModal = false;
            this.isSuccess = false;
        },
        onSelect(e) {
            this.formData.province = e.value;
        },
        init() {
            getProvinceList().then((res) => {
                console.log(res.data);
                this.provinceColumns = res.data.map((str) => {
                    return {
                        name: str,
                        value: str,
                    };
                });
            });
        },
        openModal() {
            this.showCityPicker = true;
        },
    },
};
</script>

<style lang="scss" scoped>
@import './index';
</style>
